<template>
    <div class="search-result">
        <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
        >
            <van-cell
                v-for="(item, index) in list"
                :key="index"
                :title="item.title"
                @click="$router.push({
                    name: 'article',
                    params: {
                        articleId: item.art_id.toString()
                        }
                    })"
            />
        </van-list>
    </div>
</template>

<script>
import { getSearchResult } from '@/api/search'

export default {
    props: {
        // 搜索关键词
        searchText: {
            type: String,
            required: true
        }
    },
    data () {
        return {
            list: [],
            loading: false,
            finished: false,
            page: 1,
            perPage: 20
        }
    },
    created () { },
    methods: {
        async onLoad () {
            // 发起请求
            const { data: res } = await getSearchResult({
                page: this.page,
                per_page: this.perPage,
                q: this.searchText
            })
            // console.log(res);
            // 把数据添加到数组中
            const { results } = res.data
            this.list.push(...results)

            // 关闭本次的loading
            this.loading = false

            // 判断是否还有数据
            if (results.length) {
                this.page++
            } else {
                this.finished = true
            }
        }
    }
}
</script>

<style scoped>
.search-result {
    position: fixed;
    left: 0;
    bottom: 0;
    right: 0;
    top: 54px;
    overflow-y: auto;
}
</style>
